<template>
  <el-select
    v-model="value"
    filterable
    allow-create
    default-first-option
    placeholder="选择需要查看的班级"
    @change="handleChange"
    :collapse-tags="collapseTags"
  >
    <!-- multiple -->
    <el-option
      v-for="item in getCoruses"
      :key="item.currNo"
      :label="item.label"
      :value="item"
    >
    </el-option>
  </el-select>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      options: [],
      value: {},
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      currCourses: (state) => state.courses.currCourses,
    }),
    getCoruses() {
      let data = this.options.concat(this.currCourses).map((item) => {
        return {
          label: item.name,
          value: item.currNo,
          currNo: item.currNo,
          courseID: item.courseID,
        };
      });
      return data.reduce(
        (unique, item) =>
          unique.some((uitem) => uitem.value == item.value)
            ? unique
            : [...unique, item],
        []
      );
    },
  },
  watch: {
    getCoruses(n) {
      const { id } = this.$route.params;
      const getCourse = n.find((item) => item.currNo == id);
      if (getCourse) {
        this.value = getCourse;
      }
    },
  },
  activated() {
    this.autoSelectCourse()
  },
  async created() {
    await this.$store.dispatch("courses/fetchCoursesList");
    this.autoSelectCourse()
  },
  methods: {
    autoSelectCourse() {
      if (!this.$route.params?.id) {
        this.$router.push({
          name: "Statistics",
          params: { id: this.currCourses[0].currNo },
        });
      }
    },
    handleChange(val, b, c) {
      const { currNo, courseID } = val;
      const { filter } = this.$route.query;
      this.$router.push({
        name: "Statistics",
        query: {
          currNo: currNo,
          courseID: courseID,
          filter: filter,
        },
        params: { id: currNo },
      });
    },
  },
};
</script>

<style lang="stylus" scoped></style>